<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AI视频对话</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        html, body { 
            height: 100%; 
            margin: 0; 
            padding: 0; 
            overflow: hidden;
        }
        body { 
            font-family: Arial, sans-serif; 
            display: flex;
            flex-direction: column;
        }
        body.dark-theme {
            background-color: #2c2c2c;
            color: #ffffff;
        }
        body.light-theme {
            background-color: #f0f0f0;
            color: #333333;
        }
        .container {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 0;
            max-width: 100%;
        }
        .header {
            height: 60px;
            background-color: #1a1a1a;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 15px;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1001;
        }
        .theme-toggle-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
        }
        .theme-toggle-btn img {
            width: 30px;
            height: auto;
        }
        .video-container {
            position: fixed;
            top: 70px;
            right: 10px;
            width: 160px;
            height: 120px;
            z-index: 1002;
            background-color: rgba(44, 44, 44, 0.7);
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.5);
            overflow: hidden;
            transition: all 0.3s ease;
        }
        .video-container.minimized {
            width: 40px;
            height: 40px;
        }
        #videoElement { 
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .minimize-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(0,0,0,0.5);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            line-height: 1;
            cursor: pointer;
            z-index: 1003;
        }
        .content-area {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 120px);
            margin-top: 60px;
            overflow: hidden;
        }
        #chatBox { 
            flex: 1;
            overflow-y: auto; 
            padding: 10px;
            padding-right: 180px;
            margin-bottom: 60px;
        }
        .dark-theme #chatBox {
            background-color: #3a3a3a;
        }
        .light-theme #chatBox {
            background-color: #ffffff;
        }
        .message {
            margin-bottom: 10px;
            padding: 5px 10px;
            border-radius: 5px;
            display: flex;
            align-items: flex-start;
        }
        .user-message {
            justify-content: flex-start;
        }
        .ai-message {
            justify-content: flex-start;
        }
        .message-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        .message-avatar.user-avatar {
            background-color: white;
            color: #333;
        }
        .message-avatar.ai-avatar {
            background-color: purple;
            color: white;
        }
        .message-content {
            flex: 1;
            padding: 5px 10px;
            border-radius: 5px;
        }
        .dark-theme .message-content {
            background-color: #4a4a4a;
        }
        .light-theme .message-content {
            background-color: #e0e0e0;
        }
        #loadingIndicator {
            display: none;
        }
        .input-area {
            padding: 10px;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }
        .dark-theme .input-area {
            background-color: #2c2c2c;
        }
        .light-theme .input-area {
            background-color: #d0d0d0;
        }
        #personalityModal .modal-content {
            background-color: #3a3a3a;
            color: #ffffff;
        }
        .btn-primary, .btn-info, .btn-danger {
            background-color: #007bff;
            border-color: #007bff;
            color: white;
        }
        .btn-primary:hover, .btn-info:hover, .btn-danger:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
    </style>
</head>
<body class="dark-theme">
    <div class="container">
        <div class="header">
            <h1 class="h5 m-0">AI视频对话</h1>
            <button id="themeToggle" class="theme-toggle-btn">
                <img src="bk.jpg" alt="切换主题">
            </button>
        </div>
        <div class="video-container" id="dragElement">
            <button class="minimize-btn" onclick="toggleMinimize()">_</button>
            <video id="videoElement" autoplay></video>
            <canvas id="canvas" style="display:none;"></canvas>
        </div>
        <div class="content-area">
            <div id="chatBox"></div>
        </div>
        <div class="input-area">
            <div class="input-group mb-2">
                <input type="text" id="userInput" class="form-control" placeholder="输入你的消息...">
                <button class="btn btn-primary" onclick="sendMessage()">发送</button>
            </div>
            <div class="d-flex justify-content-between">
                <button class="btn btn-secondary btn-sm" onclick="switchCamera()">切换摄像头</button>
                <button class="btn btn-primary btn-sm" onclick="openPersonalitySettings()">角色性格设定</button>
                <button class="btn btn-primary btn-sm" onclick="clearChat()">清空聊天记录</button>
            </div>
            <div id="loadingIndicator" class="mt-2">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <span>AI正在思考...</span>
            </div>
        </div>
    </div>

    <!-- 角色性格设定模态框 -->
    <div class="modal fade" id="personalityModal" tabindex="-1" aria-labelledby="personalityModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="personalityModalLabel">角色性格设定</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <textarea id="personalityInput" class="form-control" rows="5" placeholder="请输入AI角色的性格描述..."></textarea>
                    <div id="personalityExample" class="mt-2 text-muted small"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="savePersonality()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入 Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 主脚本 -->
    <script>
        const video = document.getElementById('videoElement');
        const canvas = document.getElementById('canvas');
        const chatBox = document.getElementById('chatBox');
        const userInput = document.getElementById('userInput');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const themeToggle = document.getElementById('themeToggle');
        const themeImage = themeToggle.querySelector('img');
        let stream;
        let currentFacingMode = 'user';
        let aiPersonality = localStorage.getItem('aiPersonality') || "你是一个聪明的AI，图片为监控画面，监控就是你的眼睛。";
        let isDarkTheme = true;

        async function startCamera(facingMode) {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            try {
                stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: facingMode }
                });
                video.srcObject = stream;
            } catch (err) {
                console.error("Error accessing the camera", err);
                alert("无法访问摄像头，请确保已授予权限。");
            }
        }

        function switchCamera() {
            currentFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
            startCamera(currentFacingMode);
        }

        startCamera(currentFacingMode);

        function captureImage() {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);
            return canvas.toDataURL('image/jpeg');
        }

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            const imageData = captureImage();
            appendMessage('user', message);
            userInput.value = '';
            loadingIndicator.style.display = 'block';

            try {
                const response = await fetch('这里替换你的url,支持第三方中转', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer 在这里输入你的open ai秘钥'
                    },
                    body: JSON.stringify({
                        model: "gpt-4o",
                        messages: [
                            {"role": "system", "content": aiPersonality},
                            {"role": "user", "content": [
                                {"type": "text", "text": message},
                                {"type": "image_url", "image_url": {"url": imageData}}
                            ]}
                        ],
                        max_tokens: 300,
                        stream: true
                    })
                });

                if (response.ok) {
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let aiReply = '';

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = decoder.decode(value);
                        const lines = chunk.split('\n').filter(line => line.trim() !== '');
                        
                        for (const line of lines) {
                            if (line.startsWith('data:')) {
                                try {
                                    const data = JSON.parse(line.slice(5));
                                    if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
                                        aiReply += data.choices[0].delta.content;
                                        appendMessage('ai', aiReply, true);
                                    }
                                } catch (error) {
                                    console.error('Error parsing JSON:', error);
                                }
                            }
                        }
                    }
                } else {
                    throw new Error('API response was not ok.');
                }
            } catch (error) {
                console.error('Error:', error);
                appendMessage('system', '与AI通信时出错，请稍后重试。');
            } finally {
                loadingIndicator.style.display = 'none';
            }
        }

        function appendMessage(sender, content, update = false) {
            if (update) {
                const lastMessage = chatBox.lastElementChild;
                if (lastMessage && lastMessage.classList.contains('ai-message')) {
                    lastMessage.querySelector('.message-content').textContent = content;
                } else {
                    createMessageElement(sender, content);
                }
            } else {
                createMessageElement(sender, content);
            }
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function createMessageElement(sender, content) {
            const messageElement = document.createElement('div');
            messageElement.classList.add('message', `${sender}-message`);
            
            const avatarElement = document.createElement('div');
            avatarElement.classList.add('message-avatar', `${sender}-avatar`);
            avatarElement.textContent = sender === 'user' ? '你' : 'AI';

            const contentElement = document.createElement('div');
            contentElement.classList.add('message-content');
            contentElement.textContent = content;

            messageElement.appendChild(avatarElement);
            messageElement.appendChild(contentElement);
            chatBox.appendChild(messageElement);
        }

        function clearChat() {
            chatBox.innerHTML = '';
        }

        userInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        function dragElement(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            elmnt.onmousedown = dragMouseDown;
            elmnt.ontouchstart = dragTouchStart;

            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                document.onmousemove = elementDrag;
            }

            function dragTouchStart(e) {
                e.preventDefault();
                pos3 = e.touches[0].clientX;
                pos4 = e.touches[0].clientY;
                document.ontouchend = closeDragElement;
                document.ontouchmove = elementTouchDrag;
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }

            function elementTouchDrag(e) {
                e.preventDefault();
                pos1 = pos3 - e.touches[0].clientX;
                pos2 = pos4 - e.touches[0].clientY;
                pos3 = e.touches[0].clientX;
                pos4 = e.touches[0].clientY;
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }

            function closeDragElement() {
                document.onmouseup = null;
                document.onmousemove = null;
                document.ontouchend = null;
                document.ontouchmove = null;
            }
        }

        dragElement(document.getElementById("dragElement"));

        function toggleMinimize() {
            const videoContainer = document.querySelector('.video-container');
            videoContainer.classList.toggle('minimized');
            const btn = document.querySelector('.minimize-btn');
            btn.textContent = videoContainer.classList.contains('minimized') ? '+' : '_';
        }

        function setPersonalityExample() {
            const exampleText = "示例: 你是一个聪明的ai。图片为监控画面，监控就是你的眼睛。";
            document.getElementById('personalityExample').textContent = exampleText;
        }

        function openPersonalitySettings() {
            const modal = new bootstrap.Modal(document.getElementById('personalityModal'));
            document.getElementById('personalityInput').value = aiPersonality;
            setPersonalityExample();
            modal.show();
        }

        function savePersonality() {
            const newPersonality = document.getElementById('personalityInput').value.trim();
            if (newPersonality) {
                aiPersonality = newPersonality;
                localStorage.setItem('aiPersonality', newPersonality);
                alert('角色性格设定已保存！');
                bootstrap.Modal.getInstance(document.getElementById('personalityModal')).hide();
            } else {
                alert('请输入有效的性格描述。');
            }
        }

        function toggleTheme() {
            isDarkTheme = !isDarkTheme;
            document.body.classList.toggle('light-theme', !isDarkTheme);
            document.body.classList.toggle('dark-theme', isDarkTheme);
            
            // 更新按钮图片
            themeImage.src = isDarkTheme ? 'bk.jpg' : 'qt.jpg';
            
            // 可以在这里添加其他需要随主题变化的元素样式
        }

        themeToggle.addEventListener('click', toggleTheme);
    </script>
</body>
</html>